package com.drcoffee.drcoffeemall.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 验证码相关工具类
 */
@Component
public class VerifyCodeUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 随机生成指定长度字符串验证码
     *
     * @param length 验证码长度
     */
    public static String generateVerifyCode(int length) {
        String strRange = "1234567890";
        StringBuilder strBuilder = new StringBuilder();

        for (int i = 0; i < length; ++i) {
            char ch = strRange.charAt((new Random()).nextInt(strRange.length()));
            strBuilder.append(ch);
        }
        return strBuilder.toString();
    }

    /**
     * 校验验证码
     */
    public boolean checkVerifyCode(String email, String code) {
        String verifyCode = (String) redisTemplate.opsForValue().get(email);
        if (verifyCode != null) {
            redisTemplate.delete(email);
        }
        return code.equals(verifyCode);
    }
}
